package io.kiki.sba.registry.server.clientInterface.remoting.handler;

import io.kiki.sba.registry.api.Channel;
import io.kiki.sba.registry.common.model.Node;
import io.kiki.sba.registry.common.model.client.pb.RegisterResponsePb;
import io.kiki.sba.registry.common.model.client.pb.SubscriberRegisterPb;
import io.kiki.sba.registry.core.model.RegisterResponse;
import io.kiki.sba.registry.core.model.SubscriberRegister;
import io.kiki.sba.registry.server.clientInterface.converter.pb.RegisterResponseConvertor;
import io.kiki.sba.registry.server.clientInterface.converter.pb.SubscriberRegisterConvertor;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.concurrent.Executor;


public class SubscriberPbHandler extends AbstractClientDataRequestHandler<SubscriberRegisterPb> {

    @Autowired
    SubscriberHandler subscriberHandler;

    @Override
    protected Node.NodeType getConnectNodeType() {
        return subscriberHandler.getConnectNodeType();
    }


    @Override
    public Object doHandle(Channel channel, SubscriberRegisterPb message) {


        RegisterResponsePb.Builder builder = RegisterResponsePb.newBuilder();
        SubscriberRegister register = SubscriberRegisterConvertor.convert2Java(message);
        Object response = subscriberHandler.doHandle(channel, register);
        if (!(response instanceof RegisterResponse)) {
            return builder.setSuccess(false).setMessage("Unknown response type").build();
        }

        return RegisterResponseConvertor.convert2Pb((RegisterResponse) response);
    }


    @Override
    public Class interest() {
        return SubscriberRegisterPb.class;
    }

    @Override
    public Executor getExecutor() {
        return subscriberHandler.getExecutor();
    }
}
